/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cl.uchile.microblogging.web;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cl.uchile.microblogging.persistance.UsersDAO;
import cl.uchile.microblogging.persistance.model.Session;
import cl.uchile.microblogging.persistance.model.User;

/**
 * Simple little @Controller that invokes Facebook and renders the result. The
 * injected {@link Facebook} reference is configured with the required
 * authorization credentials for the current user behind the scenes.
 * 
 * @author Keith Donald
 */
@Controller
public class HomeController {
	@Autowired
	public UsersDAO usersDAO;

	@Transactional
	@RequestMapping(value = { "/", "/login", "/newSession", "/map", "/invite" }, method = RequestMethod.GET)
	public ModelAndView home(HttpServletRequest request,
			@RequestParam(required = false) String msg) {
		String userName = (String) request.getSession().getAttribute("user");

		if (userName != null) {
			HashMap<String, Object> data = new HashMap<String, Object>();
			User user = usersDAO.byName(userName);
			data.put("name", userName);
			data.put("sessions", user.getSessions());
			data.put("msg", msg);
			return new ModelAndView("sessions", data);
		}
		return new ModelAndView("login");
	}

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String test(Model model) {
		return "fileupload";
	}

	@RequestMapping(value = "/guest", method = RequestMethod.GET)
	public String guest(Model model) {
		int random = (int) (Math.random() * ((10000) + 1));
		model.addAttribute("name", "Guest_" + random);
		return "home";
	}

	@RequestMapping(value = "/publish", method = RequestMethod.POST)
	public @ResponseBody
	String publish(@RequestParam("blogId") String blogId,
			@RequestParam("title") String title,
			@RequestParam("userName") String userName) {

		return blogId + " " + title;
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String goRegister() {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView register(@RequestParam String user,
			@RequestParam String pass) {

		if (this.usersDAO.save(new User(user, pass))) {
			return new ModelAndView("login", "msg",
					"User registered successfully");
		}
		return new ModelAndView("register", "msg", "User already registered");
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request,
			@RequestParam String user, @RequestParam String pass) {

		if (this.usersDAO.login(user, pass)) {
			request.getSession().setAttribute("user", user);
			return this.home(request, null);
		}
		return new ModelAndView("login", "msg",
				"User and/or Password are invalid");
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request) {
		request.getSession().setAttribute("user", null);
		return this.home(request, null);

	}

	@RequestMapping(value = "/newSession", method = RequestMethod.POST)
	public ModelAndView register(HttpServletRequest request,
			@RequestParam String session) {
		String userName = (String) request.getSession().getAttribute("user");
		if (this.usersDAO.save(new Session(session), userName)) {
			return this.home(request, "Session created successfully");
		}
		return this.home(request, "Session already exists");
	}

	@RequestMapping(value = "/map", method = RequestMethod.POST)
	public ModelAndView map(HttpServletRequest request,
			@RequestParam String session) {
		String userName = (String) request.getSession().getAttribute("user");
		User user = usersDAO.byName(userName);
		for (Session sessiond : user.getSessions()) {
			if (sessiond.getSessionID().equals(session)) {
				HashMap<String, Object> data = new HashMap<String, Object>();
				data.put("name", userName);
				data.put("session", session);
				data.put("sname", sessiond.getName());
				data.put("sessions", user.getSessions());
				return new ModelAndView("home", data);
			}
		}
		return this.home(request, "Permission denied");
	}

	@RequestMapping(value = "/invite", method = RequestMethod.POST)
	public ModelAndView invite(HttpServletRequest request,
			@RequestParam String session, @RequestParam String user) {

		if (this.usersDAO.joinUserToSession(user, session)) {
			return this.home(request, "User invited successfully");
		}
		return this.home(request, "User not found");
	}

}
